package com.logback.filter;

import org.slf4j.MDC;

import javax.servlet.*;
import java.io.IOException;
import java.util.UUID;

/**
 * @author chenfoxin
 * @Description 自定义全局日志拦截器
 * @Date 2022/6/6 22:49
 **/
public class TrackIdFilter implements Filter {
    public static final String UNIQUE_ID_NAME = "traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String trackId = UUID.randomUUID().toString().replace("-", "");
        MDC.put(UNIQUE_ID_NAME, trackId);
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove(UNIQUE_ID_NAME);
        }
    }
}
